import Vue from "vue";
import Toast from "./toast.vue";

const ToastClass = Vue.extend(Toast);

let instances = [];

function CreateToast(options) {
  if (Object.prototype.toString.call(options) !== "[object Object]") return;

  // 创建实例
  let instance = new ToastClass({ data: options });
  instance.$mount();

  // 绑定函数
  options.closed = () => {
    instances = instances.filter((ins) => ins !== instance);
  };

  // 添加DOM
  document.body.appendChild(instance.$el);

  // 更新高度
  let offset = options?.offset || 20;
  instances.forEach((ins) => {
    ins.$data.offset += instance.$el.offsetHeight + offset;
  });

  instances.push(instance);

  return instance;
}

["success", "error", "warning", "info"].forEach((type) => {
  CreateToast[type] = (content) => {
    let options = { content, type };
    return CreateToast(options);
  };
});

export default CreateToast;
